package com.ep.thirdPlatformProject.system.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ep.thirdPlatformProject.system.entity.SyncOARecordEntity;
import com.ep.thirdPlatformProject.system.mapper.SyncOARecordMapper;
import com.ep.thirdPlatformProject.system.service.SyncOARecordService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@DS("mysql")
@Slf4j
@RequiredArgsConstructor
public class SyncOARecordServiceImpl extends ServiceImpl<SyncOARecordMapper, SyncOARecordEntity> implements SyncOARecordService {

    private final SyncOARecordMapper mapper;

    @Override
    public Boolean findHasRecentRecordByCodeAndTime(@NotNull String empCode, Integer formId, Boolean dateLimit) {
        MPJLambdaWrapper<SyncOARecordEntity> queryWrapper = new MPJLambdaWrapper<>(SyncOARecordEntity.class)
                .selectAll()
                .eq(SyncOARecordEntity::getEmpNo, empCode)
                // 新增表单id限制
                .eq(SyncOARecordEntity::getFormId, formId)
                .eq(SyncOARecordEntity::getIsSuccess, 1);
        if (Boolean.TRUE.equals(dateLimit)) {
            DateTime date = DateUtil.date();
            // 默认最小时间为一个月前
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date dayStartTime = calendar.getTime();
            //新增时间限制
            queryWrapper.ge(SyncOARecordEntity::getCreateTime, dayStartTime);
        }

        List<SyncOARecordEntity> list = mapper.selectList(queryWrapper);

        return !list.isEmpty();
    }

    /**
     * 插入一条记录
     *
     * @param record 记录
     */
    @Override
    public void insertOneRecord(SyncOARecordEntity record) {
        try {
            this.mapper.insert(record);
        } catch (Exception e) {
            log.error("插入日志失败了：{}", e.getMessage(), e);
        }

    }


}
